package org.budo.spring.velocity.view;

import java.util.Locale;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.servlet.View;
import org.springframework.web.servlet.view.AbstractUrlBasedView;
import org.springframework.web.servlet.view.AbstractView;

/**
 * @author limingwei
 * 
 * @see org.budo.spring.velocity.view.BudoVelocityLayoutView
 * @see org.springframework.web.servlet.view.velocity.VelocityLayoutViewResolver
 */
@SuppressWarnings("deprecation")
public class BudoVelocityLayoutViewResolver extends org.springframework.web.servlet.view.velocity.VelocityLayoutViewResolver {
    private static final Logger log = LoggerFactory.getLogger(BudoVelocityLayoutViewResolver.class);

    public BudoVelocityLayoutViewResolver() {
        this.setSuffix(".vm");
        this.setContentType("text/html;charset=utf-8");
        this.setRequestContextAttribute("rc");

        this.setAllowSessionOverride(true);
        this.setAllowRequestOverride(true);
        this.setExposeSessionAttributes(true);
        this.setExposeRequestAttributes(true);
    }

    @Override
    protected Class<?> requiredViewClass() {
        return BudoVelocityLayoutView.class;
    }

    /**
     * 在这里执行 _applyLifecycleMethods
     */
    @Override
    protected AbstractUrlBasedView buildView(String viewName) throws Exception {
        AbstractUrlBasedView buildView = super.buildView(viewName);
        buildView = (AbstractUrlBasedView) this._applyLifecycleMethods(viewName, buildView); // _applyLifecycleMethods

        log.info("#46=" + buildView + ", checkResource=" + buildView.checkResource(Locale.getDefault()));
        return buildView;
    }

    /**
     * 不再执行 applyLifecycleMethods
     */
    @Override
    protected View loadView(String viewName, Locale locale) throws Exception {
        AbstractUrlBasedView view = this.buildView(viewName);
        AbstractUrlBasedView abstractUrlBasedView = view.checkResource(locale) ? view : null;

        log.info("#54 abstractUrlBasedView=" + abstractUrlBasedView);
        return view;
    }

    private View _applyLifecycleMethods(String viewName, AbstractView view) {
        return (View) this.getApplicationContext().getAutowireCapableBeanFactory().initializeBean(view, viewName);
    }
}